package com.dianping.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.PrimitiveIterator.OfDouble;

/**
 * 大众点评请求参数转换
 * 
 * @author clozz
 *
 */
public class DzOpenParamConvertUtil {

	/**
	 * <pre>
	 * 把请求参数的k-v结构转换为对象。 但是value为json的时候，任然保持json字符串，不进行转换。业务需要自行处理
	 * 
	 * @param requestMap
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
	public static <T> T convert(Map<String, String> requestMap, Class<T> clazz) {
		try {
			T t = clazz.newInstance();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				String fieldName = field.getName();
				// 字段名到参数名转换规则：所有大写字母前面加上下划线，然后变成小写字母
				// e.g.
				// userName -> user_name
				// appProductId -> app_product_id
				String paramName = fieldName.replaceAll("([A-Z])", "_$1").toLowerCase();
				if (requestMap.containsKey(paramName)) {
					String value = requestMap.get(paramName);
					field.setAccessible(true);
					field.set(t, value);
					field.setAccessible(false);
				}
			}
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Map<String, String> objectToMap(Object obj) {
		Map<String, String> map = new HashMap<>();

		Class<?> clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			String fieldName = field.getName();
			String key = fieldName.replaceAll("([A-Z])", "_$1").toLowerCase();
			field.setAccessible(true);
			try {
				String value = (String) field.get(obj);
				if (value!=null) {
					map.put(key, value);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			field.setAccessible(false);
		}
		return map;
	}
	
	
	public static String mapToString(Map<String, String> map) {
		StringBuffer sb = new StringBuffer();
		
		Set<String> keySet = map.keySet();
		
		keySet.forEach(key -> sb.append(key).append("=").append(map.get(key)).append("&"));
		
		return sb.deleteCharAt(sb.length()-1).toString();
	}

}
